package main

import (
	"context"
	"fmt"
	"github.com/robfig/cron/v3"
	"os"
	"time"
)

//	Second         ParseOption = 1 << iota // Seconds field, default 0
//	SecondOptional                         // Optional seconds field, default 0
//	Minute                                 // Minutes field, default 0
//	Hour                                   // Hours field, default 0
//	Dom                                    // Day of month field, default *
//	Month                                  // Month field, default *
//	Dow                                    // Day of week field, default *
//	DowOptional                            // Optional day of week field, default *
//	Descriptor

// 这个cron表达式不支持年份，到时候换个

const (
	ReconcileEveryWeek = "00 00 02 01,08,15 * ?"
)

func main() {
	runningCancel()
}

func runningCancel() {
	echo := &EchoJob{}
	ctx, cancelFunc := context.WithTimeout(context.Background(), 1*time.Hour)
	go echo.Run(ctx)
	var input string
	_, err := fmt.Fscan(os.Stdin, &input)
	if err != nil {
		panic(err)
	}

	if input == "stop" {
		fmt.Println("停止")
		cancelFunc()
	}
	time.Sleep(time.Second * 12)
}

type EchoJob struct {
}

func (e EchoJob) Run(ctx context.Context) {
	signal := make(chan bool)
	go e.Do(signal)
	select {
	case <-ctx.Done():
		fmt.Println("强制终止任务运行")
		return
	case <-signal:
		fmt.Println("任务正常结束")
		return
	}

}

func (e EchoJob) Do(signal chan bool) {
	count := 0
	for count < 10 {
		fmt.Println("ticking........")
		time.Sleep(2 * time.Second)
		count++
	}
	signal <- true
}

func cronRun() {
	parser := cron.NewParser(cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)

	schedule, err := parser.Parse(ReconcileEveryWeek)
	if err != nil {
		panic(err)
	}
	nextTime := time.Now()

	for i := 0; i < 10; i++ {
		nextTime = schedule.Next(nextTime)
		fmt.Println(nextTime)
	}
}
